<?php

namespace app\api\controller\kuyou\applet;

use think\Db;

class Profit extends Common
{
    public function index()
    {
        if ($this->request->isPost()) {
            $start_time = '';$end_time = '';
            $purchase_time = $this->request->post('purchase_time');
            if(!empty($purchase_time)){
                $str = explode('~',$purchase_time);
                if(isset($str[0]) && isset($str[1])){
                    $start_time = strtotime($str[0]);$end_time = strtotime($str[1]);
                }
            }
            if(empty($start_time)){
                $start_time = strtotime(date('Y-m-01'));
                $end_time = strtotime(date('Y-m-d',strtotime('+1 day')))>time()?time():strtotime(date('Y-m-d',strtotime('+1 day')));
                if($end_time>time()){
                    $end_time = time();
                }
            }

            //获取设置
            $set= \think\Db::name('kuyou_sets')->field('type,name,value,is_checked,set')->select();
            $setList = [];
            foreach ($set as $set_k=>$set_v){
                if(!empty($set_v['set'])){
                    $set_v['set'] = unserialize($set_v['set']);
                }
                $setList[$set_v['name']] = $set_v;
            }
            //数量价格格式化
            $price_decimal  = $setList['price_decimal']['value'];

            $result = ['sale_money'=>'','sales_discount'=>'','collection_all'=>'',
                'cost_all'=>'','discount_all'=>'','payment_all'=>'',
                'surplus_loss'=>'','main_business'=>'','other_income'=>'','profit'=>''];
            foreach ($result as $result_k=>$result_v){
                $result[$result_k] = round($result_v,$price_decimal);
            }
            $goods = Db::name('kuyou_goods')->where(['status'=>'1'])->select();
            foreach ($goods as $goods_k=>$goods_v){
                $res = $this->getProfit($goods_v['goods_code'],$start_time,$end_time);
                foreach ($result as $result_k=>$result_v){
                    if($result_k=='other_income'){
                        $result[$result_k] = isset($res[$result_k])?(float)$res[$result_k]:0;
                    }elseif ($result_k=='profit'){
                        $result[$result_k] += isset($res[$result_k])?(float)$res[$result_k]:0;
                        $result[$result_k] -= isset($res['other_income'])?(float)$res['other_income']:0;
                    }else{
                        $result[$result_k] += isset($res[$result_k])?(float)$res[$result_k]:0;
                    }
                }
            }

            $where = [];
            $where['examine_status'] = '1';
            if(!empty($start_time) && !empty($end_time)){
                $where['purchase_time'] = ["BETWEEN", [$start_time,$end_time]];
            }
            $discount_s = \think\Db::name('kuyou_goods_sales')->where(['purchase_type'=>1])->where($where)->sum('preferential_money');
            $discount_s2 = \think\Db::name('kuyou_goods_sales')->where(['purchase_type'=>2])->where($where)->sum('preferential_money');
            $discount_s -= $discount_s2;
            $result['main_business'] = $result['main_business']-$discount_s;
            $result['profit'] = $result['profit']-$discount_s;
            $result['sales_discount'] = $discount_s;

            $result[$result_k] += isset($res['other_income'])?(float)$res['other_income']:0;

            $profit = $this->getProfits($start_time,$end_time);
            $result['cost_all'] = $profit['sales_cost'];
            $result['sale_money'] = $profit['all_money'];
            $result['main_business'] = round($profit['all_money']-$profit['sales_cost']-$result['sales_discount']-$result['collection_all'],$price_decimal);
            $result['profit'] = round($result['main_business']+$result['other_income'],$price_decimal);


            foreach ($result as $result_k=>$result_v){
                $result[$result_k] = round($result_v,$price_decimal);
            }

            $result = array('start_time'=>date('Y-m-d',$start_time),'end_time'=>date('Y-m-d',$end_time),"data" => $result);

            if(isset($result['data'])){
                $this->success('查询成功',$result,200);
            }else{
                $this->error('查询失败','',406);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    function getProfit($goods_code,$start_time='',$end_time=''){
        //获取设置
        $set= \think\Db::name('kuyou_sets')->field('type,name,value,is_checked,set')->select();
        $setList = [];
        foreach ($set as $set_k=>$set_v){
            if(!empty($set_v['set'])){
                $set_v['set'] = unserialize($set_v['set']);
            }
            $setList[$set_v['name']] = $set_v;
        }
        //数量价格格式化
        $price_decimal  = $setList['price_decimal']['value'];

        $valuation_set= \think\Db::name('kuyou_sets')->where(['name'=>'valuation'])->value('value');//计算方法
        $stores_set= \think\Db::name('kuyou_sets')->where(['name'=>'stores'])->value('is_checked');//是否分仓
        if($valuation_set!=2){
            $valuation_set = 1;
        }
        if($stores_set!=1){
            $stores_set = 0;
        }
        $goods = \think\Db::name('kuyou_goods')->where(['goods_code'=>$goods_code])->find();
        //期初
        switch ($valuation_set){
            case 1:
                //移动平均法
                if($stores_set==1){
                    $sale_money = 0;//销售收入
                    $sales_discount = 0;//销售优惠金额
                    $collection_all = 0;//收款折扣

                    $discount_all = 0;//购货优惠金额
                    $payment_all = 0;//付款折扣

                    $surplus_loss = 0;//盘盈盘亏
                    $stores = \think\Db::name('kuyou_stores')->where(['status'=>'1'])->select();
                    foreach ($stores as $stores_k=>$stores_v){

                        //成本调整
                        $adjustment_money = 0;
                        $adjustment = \think\Db::name('kuyou_adjustment_info')->where(['goods_id'=>$goods['id'],'stores_id'=>$stores_v['id']])->select();
                        foreach ($adjustment as $adjustment_k=>$adjustment_v){
                            $advance_rate = 1;//单位换算进率
                            if($adjustment_v['goods_unit']!=$goods['unit_id']){
                                $unit = \think\Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$adjustment_v['goods_unit']])->value('advance_rate');
                                if(!empty($unit) && $unit>0){
                                    $advance_rate = $unit;
                                }
                            }
                            $money = $adjustment_v['money']/$advance_rate;//换算后的调整成本
                            $adjustment_money += $money;
                        }
                        //成本调整结束
                        //采购
                        $where = [];
                        $where['goods_code'] = $goods['goods_code'];
                        $where['stores_id'] = $stores_v['id'];
                        if(!empty($start_time) && !empty($end_time)){
                            $where['purchase_time'] = ["BETWEEN", [$start_time,$end_time]];
                        }
                        $basic_nmber = \think\Db::name('kuyou_goods_purchase_info')->where(['purchase_type'=>1])->where($where)->sum('basic_nmber');
                        $discount = \think\Db::name('kuyou_goods_purchase_info')->where(['purchase_type'=>1])->where($where)->sum('preferential_money');
                        $basic_nmber2 = \think\Db::name('kuyou_goods_purchase_info')->where(['purchase_type'=>2])->where($where)->sum('basic_nmber');
                        $discount2 = \think\Db::name('kuyou_goods_purchase_info')->where(['purchase_type'=>2])->where($where)->sum('preferential_money');
                        $basic_nmber -= $basic_nmber2;
                        $discount -= $discount2;

                        //付款折扣
                        $code = \think\Db::name('kuyou_goods_purchase_info')->where($where)->group('purchase_code')->column('purchase_code');
                        $payment_sale_id = \think\Db::name('kuyou_payment_sale')->where(['purchase_number'=>['in',$code]])->group('collection_id')->column('collection_id');
                        $payment_sale = \think\Db::name('kuyou_payment')->where(['id'=>['in',$payment_sale_id]])->sum('discount');

                        $all_money_s = \think\Db::name('kuyou_goods_sales_info')->where(['purchase_type'=>1])->where($where)->sum('all_money');
                        $discount_s = \think\Db::name('kuyou_goods_sales_info')->group('purchase_code')->where(['purchase_type'=>1])->where($where)->sum('preferential_money');
                        $all_money_s2 = \think\Db::name('kuyou_goods_sales_info')->where(['purchase_type'=>2])->where($where)->sum('all_money');
                        $discount_s2 = \think\Db::name('kuyou_goods_sales_info')->where(['purchase_type'=>2])->where($where)->sum('preferential_money');
                        $all_money_s -= $all_money_s2;
                        $discount_s -= $discount_s2;

                        //收款折扣
                        $code_s = \think\Db::name('kuyou_goods_sales_info')->where($where)->group('purchase_code')->column('purchase_code');
                        $payment_sale_s_id = \think\Db::name('kuyou_collection_sale')->where(['purchase_number'=>['in',$code_s]])->group('collection_id')->column('collection_id');
                        $payment_sale_s = \think\Db::name('kuyou_collection')->where(['id'=>['in',$payment_sale_s_id]])->sum('discount');

                        //盘盈
                        $where = [];
                        $where['goods_id'] = $goods['id'];
                        $where['stores_id'] = $stores_v['id'];
                        if(!empty($start_time) && !empty($end_time)){
                            $where['purchase_time'] = ["BETWEEN", [$start_time,$end_time]];
                        }
                        $surplus = \think\Db::name('kuyou_warehousing_info')->where($where)->sum('price');//盘盈
                        $loss = \think\Db::name('kuyou_warehouse_info')->where($where)->sum('price');//盘亏
                        $surplus_loss = $surplus_loss+$surplus-$loss;

                        if($basic_nmber>0){
                            $sale_money += $all_money_s;//销售收入
                            $sales_discount += $discount_s;//销售优惠金额
                            $collection_all += $payment_sale_s;//收款折扣

                            $discount_all += $discount;//购货优惠金额
                            $payment_all += $payment_sale;//付款折扣
                        }
                    }
                    //其他收入
                    $where = [];
                    if(!empty($start_time) && !empty($end_time)){
                        $where['purchase_time'] = ["BETWEEN", [$start_time,$end_time]];
                    }
                    $where['examine_status'] = 1;
                    $income = \think\Db::name('kuyou_income')->where($where)->sum('money');
                    $expenditure = \think\Db::name('kuyou_expenditure')->where($where)->sum('money');
                    $other_income = $income-$expenditure;

                    $main_business = $sale_money-$collection_all+$discount_all+$payment_all;
                    $profit = $other_income+$main_business;
                }else{
                    $sale_money = 0;//销售收入
                    $sales_discount = 0;//销售优惠金额
                    $collection_all = 0;//收款折扣

                    $discount_all = 0;//购货优惠金额
                    $payment_all = 0;//付款折扣

                    $surplus_loss = 0;//盘盈盘亏
                    $stores_ids = \think\Db::name('kuyou_stores')->where(['status'=>'1'])->column('id');

                    //成本调整
                    $adjustment_money = 0;
                    $adjustment = \think\Db::name('kuyou_adjustment_info')->where(['goods_id'=>$goods['id'],'stores_id'=>['in',$stores_ids]])->select();
                    foreach ($adjustment as $adjustment_k=>$adjustment_v){
                        $advance_rate = 1;//单位换算进率
                        if($adjustment_v['goods_unit']!=$goods['unit_id']){
                            $unit = \think\Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$adjustment_v['goods_unit']])->value('advance_rate');
                            if(!empty($unit) && $unit>0){
                                $advance_rate = $unit;
                            }
                        }
                        $money = $adjustment_v['money']/$advance_rate;//换算后的调整成本
                        $adjustment_money += $money;
                    }
                    //成本调整结束
                    //采购
                    $where = [];
                    $where['goods_code'] = $goods['goods_code'];
                    $where['stores_id'] = ['in',$stores_ids];
                    if(!empty($start_time) && !empty($end_time)){
                        $where['purchase_time'] = ["BETWEEN", [$start_time,$end_time]];
                    }
                    $basic_nmber = \think\Db::name('kuyou_goods_purchase_info')->where($where)->sum('basic_nmber');
                    $discount = \think\Db::name('kuyou_goods_purchase_info')->where($where)->sum('preferential_money');

                    //付款折扣
                    $code = \think\Db::name('kuyou_goods_purchase_info')->where($where)->group('purchase_code')->column('purchase_code');
                    $payment_sale_id = \think\Db::name('kuyou_payment_sale')->where(['purchase_number'=>['in',$code]])->group('collection_id')->column('collection_id');
                    $payment_sale = \think\Db::name('kuyou_payment')->where(['id'=>['in',$payment_sale_id]])->sum('discount');

                    $all_money_s = \think\Db::name('kuyou_goods_sales_info')->where($where)->sum('all_money');
                    $discount_s = \think\Db::name('kuyou_goods_sales_info')->where($where)->sum('preferential_money');

                    //收款折扣
                    $code_s = \think\Db::name('kuyou_goods_sales_info')->where($where)->group('purchase_code')->column('purchase_code');
                    $payment_sale_s_id = \think\Db::name('kuyou_collection_sale')->where(['purchase_number'=>['in',$code_s]])->group('collection_id')->column('collection_id');
                    $payment_sale_s = \think\Db::name('kuyou_collection')->where(['id'=>['in',$payment_sale_s_id]])->sum('discount');

                    //盘盈
                    $where = [];
                    $where['goods_id'] = $goods['id'];
                    $where['stores_id'] = ['in',$stores_ids];
                    if(!empty($start_time) && !empty($end_time)){
                        $where['purchase_time'] = ["BETWEEN", [$start_time,$end_time]];
                    }
                    $surplus = \think\Db::name('kuyou_warehousing_info')->where($where)->sum('price');//盘盈
                    $loss = \think\Db::name('kuyou_warehouse_info')->where($where)->sum('price');//盘亏
                    $surplus_loss = $surplus_loss+$surplus-$loss;

                    if($basic_nmber>0){
                        $sale_money += $all_money_s;//销售收入
                        $sales_discount += $discount_s;//销售优惠金额
                        $collection_all += $payment_sale_s;//收款折扣

                        $discount_all += $discount;//购货优惠金额
                        $payment_all += $payment_sale;//付款折扣
                    }
                    //其他收入
                    $where = [];
                    if(!empty($start_time) && !empty($end_time)){
                        $where['purchase_time'] = ["BETWEEN", [$start_time,$end_time]];
                    }
                    $where['examine_status'] = 1;
                    $income = \think\Db::name('kuyou_income')->where($where)->sum('money');
                    $expenditure = \think\Db::name('kuyou_expenditure')->where($where)->sum('money');
                    $other_income = $income-$expenditure;

                    $main_business = $sale_money-$collection_all+$discount_all+$payment_all;
                    $profit = $other_income+$main_business;
                }
                return ['sale_money'=>$sale_money,'sales_discount'=>$sales_discount,'collection_all'=>$collection_all,
                    'cost_all'=>0,'discount_all'=>$discount_all,'payment_all'=>$payment_all,
                    'surplus_loss'=>$surplus_loss,'main_business'=>$main_business,'other_income'=>$other_income,'profit'=>$profit];
                break;
            case 2:
                //先进先出法
                if($stores_set==1){
                    $sale_money = 0;//销售收入
                    $sales_discount = 0;//销售优惠金额
                    $collection_all = 0;//收款折扣

                    $discount_all = 0;//购货优惠金额
                    $payment_all = 0;//付款折扣

                    $surplus_loss = 0;//盘盈盘亏
                    $stores = \think\Db::name('kuyou_stores')->where(['status'=>'1'])->select();
                    foreach ($stores as $stores_k=>$stores_v){
                        //期初
                        $goods_period = \think\Db::name('kuyou_goods_period')->where(['goods_code'=>$goods['goods_code'],'stores_id'=>$stores_v['id']])->sum('period');
                        $goods_period_money = \think\Db::name('kuyou_goods_period')->where(['goods_code'=>$goods['goods_code'],'stores_id'=>$stores_v['id']])->sum('price');

                        //成本调整
                        $adjustment_money = 0;
                        $adjustment = \think\Db::name('kuyou_adjustment_info')->where(['goods_id'=>$goods['id'],'stores_id'=>$stores_v['id']])->select();
                        foreach ($adjustment as $adjustment_k=>$adjustment_v){
                            $advance_rate = 1;//单位换算进率
                            if($adjustment_v['goods_unit']!=$goods['unit_id']){
                                $unit = \think\Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$adjustment_v['goods_unit']])->value('advance_rate');
                                if(!empty($unit) && $unit>0){
                                    $advance_rate = $unit;
                                }
                            }
                            $money = $adjustment_v['money']/$advance_rate;//换算后的调整成本
                            $adjustment_money += $money;
                        }
                        //成本调整结束

                        $where = [];
                        $where['goods_code'] = $goods['goods_code'];
                        $where['stores_id'] = $stores_v['id'];
                        if(!empty($start_time) && !empty($end_time)){
                            $where['purchase_time'] = ["BETWEEN", [$start_time,$end_time]];
                        }

                        $basic_nmber_s = \think\Db::name('kuyou_goods_sales_info')->where($where)->sum('basic_nmber');
                        $all_money_s = \think\Db::name('kuyou_goods_sales_info')->where($where)->sum('all_money');
                        $discount_s = \think\Db::name('kuyou_goods_sales_info')->where($where)->sum('preferential_money');

                        //收款折扣
                        $code_s = \think\Db::name('kuyou_goods_sales_info')->where($where)->group('purchase_code')->column('purchase_code');
                        $payment_sale_s_id = \think\Db::name('kuyou_collection_sale')->where(['purchase_number'=>['in',$code_s]])->group('collection_id')->column('collection_id');
                        $payment_sale_s = \think\Db::name('kuyou_collection')->where(['id'=>['in',$payment_sale_s_id]])->sum('discount');

                        $cost = 0;
                        if($basic_nmber_s>$goods_period){
                            $basic_nmber_s -= $goods_period;
                            $cost += $goods_period_money;
                        }else{
                            $basic_nmber_s = 0;
                            $cost += $goods_period_money/$goods_period*$basic_nmber_s;
                        }
                        //采购
                        $basic_nmber_all = $basic_nmber_s;
                        \think\Db::name('kuyou_goods_purchase_info')
                            ->where($where)
                            ->chunk(100, function($orderList) use ($basic_nmber_all,$cost){
                                foreach ($orderList as $order) {
                                    if($basic_nmber_all>0){
                                        if($order['basic_nmber']>$basic_nmber_all){
                                            $now_nmber = $order['basic_nmber']-$basic_nmber_all;
                                            $now_money = $now_nmber*$order['unit_price'];
                                            $basic_nmber_all -= $now_nmber;
                                            $cost += $now_money;
                                        }else{
                                            $cost += $order['all_money'];
                                            $basic_nmber_all -= $order['basic_nmber'];
                                        }
                                    }
                                }
                            });

                        $discount = \think\Db::name('kuyou_goods_purchase_info')->where($where)->sum('preferential_money');

                        //付款折扣
                        $code = \think\Db::name('kuyou_goods_purchase_info')->where($where)->group('purchase_code')->column('purchase_code');
                        $payment_sale_id = \think\Db::name('kuyou_payment_sale')->where(['purchase_number'=>['in',$code]])->group('collection_id')->column('collection_id');
                        $payment_sale = \think\Db::name('kuyou_payment')->where(['id'=>['in',$payment_sale_id]])->sum('discount');


                        //盘盈
                        $where = [];
                        $where['goods_id'] = $goods['id'];
                        $where['stores_id'] = $stores_v['id'];
                        if(!empty($start_time) && !empty($end_time)){
                            $where['purchase_time'] = ["BETWEEN", [$start_time,$end_time]];
                        }
                        $surplus = \think\Db::name('kuyou_warehousing_info')->where($where)->sum('price');//盘盈
                        $loss = \think\Db::name('kuyou_warehouse_info')->where($where)->sum('price');//盘亏
                        $surplus_loss = $surplus_loss+$surplus-$loss;

                        $sale_money += $all_money_s;//销售收入
                        $sales_discount += $discount_s;//销售优惠金额
                        $collection_all += $payment_sale_s;//收款折扣

                        $discount_all += $discount;//购货优惠金额
                        $payment_all += $payment_sale;//付款折扣
                    }
                    //其他收入
                    $where = [];
                    if(!empty($start_time) && !empty($end_time)){
                        $where['purchase_time'] = ["BETWEEN", [$start_time,$end_time]];
                    }
                    $where['examine_status'] = 1;
                    $income = \think\Db::name('kuyou_income')->where($where)->sum('money');
                    $expenditure = \think\Db::name('kuyou_expenditure')->where($where)->sum('money');
                    $other_income = $income-$expenditure;

                    $main_business = $sale_money-$collection_all+$discount_all+$payment_all;
                    $profit = $other_income+$main_business;
                }else{
                    $sale_money = 0;//销售收入
                    $sales_discount = 0;//销售优惠金额
                    $collection_all = 0;//收款折扣

                    $cost_all = 0;//销售成本
                    $discount_all = 0;//购货优惠金额
                    $payment_all = 0;//付款折扣

                    $surplus_loss = 0;//盘盈盘亏
                    $stores_ids = \think\Db::name('kuyou_stores')->where(['status'=>'1'])->column('id');
                    //期初
                    $goods_period = \think\Db::name('kuyou_goods_period')->where(['goods_code'=>$goods['goods_code'],'stores_id'=>['in',$stores_ids]])->sum('period');
                    $goods_period_money = \think\Db::name('kuyou_goods_period')->where(['goods_code'=>$goods['goods_code'],'stores_id'=>['in',$stores_ids]])->sum('price');

                    //成本调整
                    $adjustment_money = 0;
                    $adjustment = \think\Db::name('kuyou_adjustment_info')->where(['goods_id'=>$goods['id'],'stores_id'=>['in',$stores_ids]])->select();
                    foreach ($adjustment as $adjustment_k=>$adjustment_v){
                        $advance_rate = 1;//单位换算进率
                        if($adjustment_v['goods_unit']!=$goods['unit_id']){
                            $unit = \think\Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$adjustment_v['goods_unit']])->value('advance_rate');
                            if(!empty($unit) && $unit>0){
                                $advance_rate = $unit;
                            }
                        }
                        $money = $adjustment_v['money']/$advance_rate;//换算后的调整成本
                        $adjustment_money += $money;
                    }
                    //成本调整结束

                    $where = [];
                    $where['goods_code'] = $goods['goods_code'];
                    $where['stores_id'] = ['in',$stores_ids];
                    if(!empty($start_time) && !empty($end_time)){
                        $where['purchase_time'] = ["BETWEEN", [$start_time,$end_time]];
                    }

                    $basic_nmber_s = \think\Db::name('kuyou_goods_sales_info')->where($where)->sum('basic_nmber');
                    $all_money_s = \think\Db::name('kuyou_goods_sales_info')->where($where)->sum('all_money');
                    $discount_s = \think\Db::name('kuyou_goods_sales_info')->where($where)->sum('preferential_money');

                    //收款折扣
                    $code_s = \think\Db::name('kuyou_goods_sales_info')->where($where)->group('purchase_code')->column('purchase_code');
                    $payment_sale_s_id = \think\Db::name('kuyou_collection_sale')->where(['purchase_number'=>['in',$code_s]])->group('collection_id')->column('collection_id');
                    $payment_sale_s = \think\Db::name('kuyou_collection')->where(['id'=>['in',$payment_sale_s_id]])->sum('discount');

                    $cost = 0;
                    if($basic_nmber_s>$goods_period){
                        $basic_nmber_s -= $goods_period;
                        $cost += $goods_period_money;
                    }else{
                        $basic_nmber_s = 0;
                        if($goods_period>0){
                            $cost += $goods_period_money/$goods_period*$basic_nmber_s;
                        }else{
                            $cost += 0;
                        }
                    }
                    //采购
                    $basic_nmber_all = $basic_nmber_s;
                    \think\Db::name('kuyou_goods_purchase_info')
                        ->where($where)
                        ->chunk(1, function($orderList) use (&$basic_nmber_all,&$cost){
                            foreach ($orderList as $order) {
                                if($basic_nmber_all>0){
                                    if($order['basic_nmber']>$basic_nmber_all){
                                        $now_nmber = $order['basic_nmber']-$basic_nmber_all;
                                        $now_money = $now_nmber*$order['unit_price'];
                                        $basic_nmber_all -= $now_nmber;
                                        $cost += $now_money;
                                    }else{
                                        $cost += $order['all_money'];
                                        $basic_nmber_all -= $order['basic_nmber'];
                                    }
                                }
                            }
                        });
                    $discount = \think\Db::name('kuyou_goods_purchase_info')->where($where)->sum('preferential_money');

                    //付款折扣
                    $code = \think\Db::name('kuyou_goods_purchase_info')->where($where)->group('purchase_code')->column('purchase_code');
                    $payment_sale_id = \think\Db::name('kuyou_payment_sale')->where(['purchase_number'=>['in',$code]])->group('collection_id')->column('collection_id');
                    $payment_sale = \think\Db::name('kuyou_payment')->where(['id'=>['in',$payment_sale_id]])->sum('discount');


                    //盘盈
                    $where = [];
                    $where['goods_id'] = $goods['id'];
                    $where['stores_id'] = ['in',$stores_ids];
                    if(!empty($start_time) && !empty($end_time)){
                        $where['purchase_time'] = ["BETWEEN", [$start_time,$end_time]];
                    }
                    $surplus = \think\Db::name('kuyou_warehousing_info')->where($where)->sum('price');//盘盈
                    $loss = \think\Db::name('kuyou_warehouse_info')->where($where)->sum('price');//盘亏
                    $surplus_loss = $surplus_loss+$surplus-$loss;

                    $sale_money += $all_money_s;//销售收入
                    $sales_discount += $discount_s;//销售优惠金额
                    $collection_all += $payment_sale_s;//收款折扣

                    $discount_all += $discount;//购货优惠金额
                    $payment_all += $payment_sale;//付款折扣
                    //其他收入
                    $where = [];
                    if(!empty($start_time) && !empty($end_time)){
                        $where['purchase_time'] = ["BETWEEN", [$start_time,$end_time]];
                    }
                    $where['examine_status'] = 1;
                    $income = \think\Db::name('kuyou_income')->where($where)->sum('money');
                    $expenditure = \think\Db::name('kuyou_expenditure')->where($where)->sum('money');
                    $other_income = $income-$expenditure;

                    $main_business = $sale_money-$collection_all+$discount_all+$payment_all;
                    $profit = $other_income+$main_business;
                }
                return ['sale_money'=>$sale_money,'sales_discount'=>$sales_discount,'collection_all'=>$collection_all,
                    'cost_all'=>0,'discount_all'=>$discount_all,'payment_all'=>$payment_all,
                    'surplus_loss'=>$surplus_loss,'main_business'=>$main_business,'other_income'=>$other_income,'profit'=>$profit];
                break;
            default:
                return ['sale_money'=>'','sales_discount'=>'','collection_all'=>'',
                    'cost_all'=>'','discount_all'=>'','payment_all'=>'',
                    'surplus_loss'=>'','main_business'=>'','other_income'=>'','profit'=>''];
                break;
        }
    }
    function getProfits($start_time,$end_time)
    {
        $sort = 'purchase_time';$order='ASC';
        $checkdate = Db::name('kuyou_checkout')->order(['checkdate'=>'DESC'])->value('checktime');
        $map = [];
        if(!empty($checkdate)){
            $map['purchase_time'] = ['>',$checkdate];
        }
        $lists = Db::name('kuyou_goods_sales_profit')
            ->where($map)
            ->order($sort, $order)
            ->select();

        $where = [];
        $where['purchase_time'] = ['BETWEEN',[$start_time,$end_time]];
        $list = Db::name('kuyou_goods_sales_profit')
            ->where($where)
            ->order($sort, $order)
            ->select();

        $price_decimal = \think\Db::name('kuyou_sets')->where(['name'=>'price_decimal'])->value('value');
        $all_money_all = 0;$profit_all = 0;$net_profit_add = 0;

        $valuation_set= \think\Db::name('kuyou_sets')->where(['name'=>'valuation'])->value('value');//计算方法
        $stores_set= \think\Db::name('kuyou_sets')->where(['name'=>'stores'])->value('is_checked');//是否分仓
        if($valuation_set!=2){
            $valuation_set = 1;
        }
        if($stores_set!=1){
            $stores_set = 0;
        }

        $goods_info = [];
        foreach ($lists as $list_k=>$list_v){
            $cost_all = 0;$pay_money = 0;
            if($list_v['purchase_type']==1){
                $info = Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>$list_v['purchase_code']])->field('pay_money,basic_nmber,goods_code,stores_id,purchase_time')->select();
                foreach ($info as $info_k=>$info_v){

                    if(!isset($goods_info[$info_v['goods_code']])){
                        $where = [];
                        $stores_ids = \think\Db::name('kuyou_stores')->where(['status'=>'1'])->column('id');
                        if($stores_set==1){
                            $where['stores_id'] = ['in',$stores_ids];
                        }else{
                            $where['stores_id'] = $info_v['stores_id'];
                        }
                        $where['goods_code'] = $info_v['goods_code'];

                        $checkdate = Db::name('kuyou_checkout')->order(['checkdate'=>'DESC'])->value('checktime');
                        if(empty($checkdate)){
                            $enable_time = Db::name('kuyou_sets')->where(['name'=>'enable_time'])->value('value');
                            $start_time = strtotime($enable_time);

                            $end_time = strtotime(date('Y-m-d',$info_v['purchase_time']).' 23:59:59');
                            $wheretime['start_time'] = $start_time;
                            $wheretime['end_time'] = $end_time;
                            if(!empty($wheretime)){
                                $where['purchase_time'] = ['between',[$wheretime['start_time'],time()]];
                            }
                            if($valuation_set==1){
                                $purchase_info = Db::name('kuyou_goods_purchase_info')->where($where)->group('purchase_time')
                                    ->field('purchase_time,sum(basic_nmber) as basic_nmber,sum(all_money) as all_money')
                                    ->order(['purchase_time'=>'ASC'])->select();
                            }else{
                                $purchase_info = Db::name('kuyou_goods_purchase_info')->where($where)
                                    ->field('purchase_time,basic_nmber,all_money')
                                    ->order(['purchase_time'=>'ASC','purchase_code'=>'ASC'])->select();
                            }
                        }else{
                            $checkout_id = Db::name('kuyou_checkout')->order(['checkdate'=>'DESC'])->value('id');
                            $purchase_more = Db::name('kuyou_checkout_info')->where([
                                'checkout_id'=>$checkout_id,
                                'goods_code'=>$info_v['goods_code'],
                            ])->find();
                            $purchase_infos = Db::name('kuyou_goods_purchase')->where(['id'=>$purchase_more['purchase_id']])->find();

                            $start_time = $checkdate;
                            $end_time = strtotime(date('Y-m-d',$info_v['purchase_time']).' 23:59:59');
                            $wheretime['start_time'] = $start_time;
                            $wheretime['end_time'] = $end_time;
                            if(!empty($wheretime)){
                                $where['purchase_time'] = ['between',[$wheretime['start_time'],time()]];
                            }
                            if($valuation_set==1){
                                $purchase_info = Db::name('kuyou_goods_purchase_info')->where($where)->group('purchase_time')
                                    ->field('purchase_time,sum(basic_nmber) as basic_nmber,sum(all_money) as all_money')
                                    ->order(['purchase_time'=>'ASC'])->select();
                                if(!empty($purchase_more)){
                                    foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                                        if($purchase_info_v['purchase_time']==$purchase_more['purchase_time']){
                                            $purchase_info[$purchase_info_k]['basic_nmber'] = (float)$purchase_more['av_basic_nmber'];
                                            $purchase_info[$purchase_info_k]['all_money'] = (float)$purchase_more['av_all_money'];
                                        }
                                    }
                                }
                            }else{
                                if(empty($purchase_more)){
                                    $purchase_info = Db::name('kuyou_goods_purchase_info')->where($where)
                                        ->field('purchase_time,basic_nmber,all_money')
                                        ->order(['purchase_time'=>'ASC','purchase_code'=>'ASC'])->select();
                                }else{
                                    $where['purchase_code'] = ['>=',$purchase_infos['purchase_code']];
                                    $purchase_info = Db::name('kuyou_goods_purchase_info')->where($where)
                                        ->field('id,purchase_time,basic_nmber,all_money')
                                        ->order(['purchase_time'=>'ASC','purchase_code'=>'ASC'])->select();
                                    foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                                        if($purchase_info_v['id']==$purchase_more['purchase_id']){
                                            $purchase_info[$purchase_info_k]['basic_nmber'] = (float)$purchase_more['basic_nmber'];
                                            $purchase_info[$purchase_info_k]['all_money'] = (float)$purchase_more['all_money'];
                                        }
                                    }
                                }
                            }
                        }


                        $where = [];
                        $where['goods_code'] = $info_v['goods_code'];
                        $where['stores_id'] = ['in',$stores_ids];
                        if(!empty($wheretime)){
                            $where['createtime'] = ['between',[$wheretime['start_time'],time()]];
                        }
                        //期初
                        $period = Db::name('kuyou_goods_period')->where($where)->field('period as basic_nmber,price as all_money,createtime as purchase_time')->find();
                        if(!empty($period)){
                            $period['purchase_time'] = strtotime(date('Y-m-d',$period['purchase_time']));
                            if($valuation_set==1){
                                $status = true;
                                foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                                    if($purchase_info_v['purchase_time']==$period['purchase_time']){
                                        $status = false;
                                        $purchase_info[$purchase_info_k]['basic_nmber'] += $period['basic_nmber'];
                                        $purchase_info[$purchase_info_k]['all_money'] += $period['all_money'];
                                    }
                                }
                                if($status){
                                    $purchase_info[] = $period;
                                    $purchase_info = (new Commons())->arraySequence($purchase_info,'purchase_time','SORT_ASC');
                                }
                            }else{
                                $purchase_infos = [];
                                $purchase_infos[] = $period;
                                foreach ($purchase_info as $k=>$v){
                                    $purchase_infos[] = $v;
                                }
                                $purchase_info = $purchase_infos;
                            }
                        }

                        $goods = Db::name('kuyou_goods')->where(['goods_code'=>$info_v['goods_code']])->field('id,unit_id')->find();
                        if($goods){
                            $where = [];
                            $where['goods_id'] = $goods['id'];
                            $where['stores_id'] = ['in',$stores_ids];
                            if(!empty($wheretime)){
                                $where['purchase_time'] = ['between',[$wheretime['start_time'],time()]];
                            }
                            //成本调整
                            $adjustment_money = 0;
                            $adjustment = \think\Db::name('kuyou_adjustment_info')->where($where)->select();
                            foreach ($adjustment as $adjustment_k=>$adjustment_v){
                                $advance_rate = 1;//单位换算进率
                                if($adjustment_v['goods_unit']!=$goods['unit_id']){
                                    $unit = \think\Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$adjustment_v['goods_unit']])->value('advance_rate');
                                    if(!empty($unit) && $unit>0){
                                        $advance_rate = $unit;
                                    }
                                }
                                $money = $adjustment_v['money']/$advance_rate;//换算后的调整成本
                                $adjustment[$adjustment_k]['purchase_time'] = strtotime(date('Y-m-d',$adjustment_v['purchase_time']));
                                $adjustment[$adjustment_k]['all_money'] = $adjustment_v['money'];
                            }
                            foreach ($adjustment as $adjustment_k=>$adjustment_v){
                                foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                                    if($purchase_info_v['purchase_time']==$adjustment_v['purchase_time']){
                                        $purchase_info[$purchase_info_k]['all_money'] += $adjustment_v['all_money'];
                                    }
                                }
                            }
                            //成本调整结束
                        }
                    }else{
                        $purchase_info = $goods_info[$info_v['goods_code']];
                    }

                    $cost = (new Goods())->getCost_Price($info_v['goods_code'],'',$info_v['basic_nmber'],$purchase_info);

                    if(isset($cost['purchase_info'])){
                        $goods_info[$info_v['goods_code']] = $cost['purchase_info'];
                        $purchase_info = $goods_info[$info_v['goods_code']];
                        $cost = $cost['cost'];
                    }
                    $cost_all += $cost*$info_v['basic_nmber'];
                    $pay_money += $info_v['pay_money'];
                }
            }
            $lists[$list_k]['pay_money'] = $pay_money;
            $lists[$list_k]['sales_cost'] = round($cost_all,$price_decimal);
            $lists[$list_k]['profit'] = round($list_v['all_money']-$cost_all,$price_decimal);
            if($list_v['all_money']>0){
                $lists[$list_k]['profit_rate'] = round($lists[$list_k]['profit']/$list_v['all_money']*100,2);
            }else{
                $lists[$list_k]['profit_rate'] = 0;
            }
            $lists[$list_k]['net_profit'] = round($lists[$list_k]['profit']-$list_v['preferential_money']-$list_v['purchase_money'],$price_decimal);
            if($list_v['all_money']>0){
                $lists[$list_k]['net_profit_rate'] = round($lists[$list_k]['net_profit']/$list_v['all_money']*100,2);
            }else{
                $lists[$list_k]['net_profit_rate'] = 0;
            }
        }

        foreach ($list as $list_k=>$list_v){
            $status = true;
            foreach ($lists as $lists_k=>$lists_v){
                if($list_v['id']==$lists_v['id']){
                    $status = false;
                    $list[$list_k]['pay_money'] = $lists[$lists_k]['pay_money'];
                    $list[$list_k]['sales_cost'] = $lists[$lists_k]['sales_cost'];
                    $list[$list_k]['profit'] = $lists[$lists_k]['profit'];
                    $list[$list_k]['profit_rate'] = $lists[$lists_k]['profit_rate'];
                    $list[$list_k]['net_profit'] = $lists[$lists_k]['net_profit'];
                    $list[$list_k]['net_profit_rate'] = $lists[$lists_k]['net_profit_rate'];
                    $all_money_all += $lists[$lists_k]['all_money'];
                    $profit_all += $lists[$lists_k]['profit'];
                    $net_profit_add += $lists[$lists_k]['net_profit'];
                }
            }
            if($status){
                $cost_all = $list_v['sales_cost'];
                $list[$list_k]['sales_cost'] = round($cost_all,$price_decimal);
                $list[$list_k]['profit'] = round($list_v['all_money']-$cost_all,$price_decimal);
                if($list_v['all_money']>0){
                    $list[$list_k]['profit_rate'] = round($list[$list_k]['profit']/$list_v['all_money']*100,2);
                }else{
                    $list[$list_k]['profit_rate'] = 0;
                }
                $list[$list_k]['net_profit'] = round($list[$list_k]['profit']-$list_v['preferential_money']-$list_v['purchase_money'],$price_decimal);
                if($list_v['all_money']>0){
                    $list[$list_k]['net_profit_rate'] = round($list[$list_k]['net_profit']/$list_v['all_money']*100,2);
                }else{
                    $list[$list_k]['net_profit_rate'] = 0;
                }
            }
        }

        $sales_cost = 0;$all_money = 0;
        foreach ($list as $list_k=>$list_v){
            $sales_cost += $list_v['sales_cost'];
            $all_money += $list_v['all_money'];
        }
        return ['sales_cost'=>$sales_cost,'all_money'=>$all_money];
    }
}
